<template>
  <div v-if="hasError" class="error-boundary">
    <div class="error-content">
      <el-icon size="64" color="#f56c6c"><Warning /></el-icon>
      <h3>页面加载出错</h3>
      <p>{{ errorMessage }}</p>
      <div class="error-actions">
        <el-button type="primary" @click="retry">重试</el-button>
        <el-button @click="goHome">返回首页</el-button>
      </div>
    </div>
  </div>
  <slot v-else />
</template>

<script setup lang="ts">
import { ref, onErrorCaptured } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const hasError = ref(false)
const errorMessage = ref('')

onErrorCaptured((error: Error) => {
  console.error('组件错误:', error)
  hasError.value = true
  errorMessage.value = error.message || '未知错误'
  return false
})

const retry = () => {
  hasError.value = false
  errorMessage.value = ''
  window.location.reload()
}

const goHome = () => {
  hasError.value = false
  errorMessage.value = ''
  router.push('/')
}
</script>

<style lang="scss" scoped>
.error-boundary {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .error-content {
    text-align: center;
    padding: 40px;
    
    h3 {
      margin: 20px 0 10px 0;
      color: #303133;
    }
    
    p {
      color: #909399;
      margin-bottom: 30px;
    }
    
    .error-actions {
      display: flex;
      gap: 12px;
      justify-content: center;
    }
  }
}
</style>
